
using UnityEditor;
using UnityEngine;
using HotUpdate.Core.Editor;
using System.Collections.Generic;
namespace HotUpdate.Editor {
    [CustomPropertyDrawer(typeof(TypeNameSelectAttribute))]
    public class TypeNameSelectAttributeDrawer : PropertyDrawer
    {        
        List<string> m_TypeNames = new List<string>();
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            m_TypeNames.Clear();
            TypeNameSelectAttribute attr = attribute as TypeNameSelectAttribute;
            if (attr.AllowEmpty)
            {
                m_TypeNames.Add("[空]");
            }
            m_TypeNames.AddRange(Type.GetRuntimeTypeNames(attr.BaseType));
            var namesArray = m_TypeNames.ToArray();
            int nameIndex = -1;
            if (property.stringValue != null)
            {
                for (int i = 0; i < namesArray.Length; i++)
                {
                    if(attr.AllowEmpty && i==0 && string.IsNullOrEmpty(property.stringValue))
                    {
                        nameIndex = 0;
                        break;
                    }
                    if (namesArray[i] == property.stringValue)
                    {
                        nameIndex = i;
                        break;
                    }
                }
            }
            var selected = EditorGUI.Popup(position,property.displayName,nameIndex,namesArray);
            if(selected!=-1)
            {
                if(attr.AllowEmpty && selected==0)
                {
                    property.stringValue = string.Empty;
                }
                else
                {
                    property.stringValue = namesArray[selected];
                }
            }
        }

    }

}

